package com.sxf.core.aspect;

import com.sxf.auth.login.vo.LoginRes;
import com.sxf.common.param.BaseVO;
import com.sxf.common.param.PageBaseVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 切面注入入参用户信息
 *
 * @author leo
 * @version 1.0
 * @date 2022年08月03日
 */
@Component
@Aspect
public class UserAspect {

    @Pointcut("execution(* com.sxf..controller.*Controller.*(..)) ")
    public void controllerAspect() {
    }

    @Around("controllerAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return joinPoint.proceed(args);
        }

        LoginRes loginRes = UserThreadLocal.get();

        if (!Objects.isNull(loginRes)) {
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                Object arg = joinPoint.getArgs()[i];
                //防止参数为空
                if (Objects.isNull(arg)) {
                    Class<?> type = ((MethodSignature) joinPoint.getSignature()).getMethod().getParameterTypes()[i];
                    arg = type.getDeclaredConstructor().newInstance();
                }
                if (arg instanceof BaseVO) {
                    BaseVO baseVo = (BaseVO) arg;
                    baseVo.setUserId(loginRes.getPkUser());
                    baseVo.setCurName(loginRes.getUserName());
                    baseVo.setUserType(loginRes.getUserType());
                    baseVo.setClient(ClientThreadLocal.get());
                    joinPoint.getArgs()[i] = arg;
                }
                if (arg instanceof PageBaseVO) {
                    PageBaseVO baseVo = (PageBaseVO) arg;
                    baseVo.setUserId(loginRes.getPkUser());
                    baseVo.setCurName(loginRes.getUserName());
                    baseVo.setUserType(loginRes.getUserType());
                    baseVo.setClient(ClientThreadLocal.get());
                    joinPoint.getArgs()[i] = arg;
                }
            }
        }
        return joinPoint.proceed(args);
    }
}

